package com.efeichong.common.security;

import com.efeichong.common.domain.ResponseData;
import com.efeichong.common.domain.entity.redis.LoginUser;
import com.efeichong.common.domain.repository.redis.LoginUserRepository;
import com.efeichong.common.utils.ResponseUtils;
import com.efeichong.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lxk
 * @date 2020/9/4
 * @description 登陆过期验证过滤
 */
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    private LoginUserRepository loginUserRepository;
    @Value("${token.header}")
    private String tokenHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String token = request.getHeader(tokenHeader);
        if (EntityUtils.isNotEmpty(token)) {
            LoginUser loginUser = loginUserRepository.findByToken(token);
            if (loginUser != null) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                chain.doFilter(request, response);
            } else {
                ResponseUtils.format(response, request, ResponseData.loginExpire());
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}
